import store from '../../westore/store'
import create from '../../westore/utils/create'

import Api from "../../utils/api"
import Config from "../../config"
const player = wx.getBackgroundAudioManager()
// player.src = Config.baseUrl + "musics/3/1/music_1.mp3"
// wx.getBackgroundAudioManager  createInnerAudioContext
create(store, {
  data: {
    inMePage: false,
    openid: "",
    userState: {},
    introVisible: false,
    taskData: [],
    timers: [],
    taskDataDetailIndex: 0,
    onMusicPlaying: false,
    onMusicEnd: false,
    sharePicShow: false,
    progress: "0%",
    tips: [
      "在体验过程中有任何疑问，欢迎来「社区」互动！",
      "为您的坚持点赞。每天3分钟，轻松减压，积蓄力量，继续向前行。欢迎参与「社区」互动。",
      "欢迎您参与「社区」互动，分享感受，让更多人得到启发。",
      "连续坚持7天了，为您点赞。欢迎参与「社区」互动，分享您的感受或困惑。",
      "恭喜您连续坚持14天，这是一个可喜的成就。欢迎参与「社区」互动，分享您的心得。",
      "恭喜您连续坚持21天！欢迎继续坚持，欢迎您到「社区」分享感受，帮助更多人轻松减压，用更好的状态，向前行。"],
    tip: "在体验过程中有任何疑问，欢迎来「社区」互动！"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function () {
    setPlayer.call(this)  // 监听播放事件
    wx.showLoading({
      title: '加载中',
    })
    var _this = this;
    const openid = this.data.openid || await Api.Login();
    _this.getTaskList(openid)
    var res = await Api.getUserInfo(openid)

    if (res.status == 0) {
      _this.store.data.openid = openid;
      _this.store.data.userState = res.encryptedData.data;
      _this.store.data.userInfo = res.userInfo;
      _this.update()
    } else {
      this.navToPlanPage()
    }
    wx.hideLoading();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    this.data.openid && this.getTaskList(this.data.openid)
    this.setData({
      timers: [],
    })
    setTimeout(() => {
      this.setData({
        inMePage: true
      })
    }, 100);
    if (this.data.onMusicPlaying) {
      player.play()
    }
  },
  onHide() {
    this.setData({
      inMePage: false
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      inMePage: false
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    return {
      imageUrl: '/assets/images/share-pic.png',
    }
  },

  async getTaskList(openid) {
    const setting = await Api.getAllSetting(openid);
    if (setting.status == 0) {
      if (setting.data.length > 0) {
        this.store.data.settingList = setting.data
        var res = await Api.getSettingById(openid, setting.data[0].id);
        this.setData({
          taskData: res.data
        });
        // 完成所有任务
        (res.data.detail.filter(each => {
          if (each.complete == 0) {
            return each
          }
        }).length == 0 && res.data.custom == 0) && wx.showToast({
          title: '您已完成所有任务，快去重设新的计划吧',
          icon: 'none'
        })




        if (!this.data.timers.length) { // 有可能是刚听完
          this.setData({
            timers: (() => new Array(res.data.detail.length))()
          })
        }
      } else {
        this.navToPlanPage()
      }
    } else {
      // wx.hideLoading();
      // wx.showToast({
      //   title: '获取数据失败，请重试',
      //   icon: 'none'
      // })
    }
  },

  toggleIntroVisible(e) {
    this.setData({
      introVisible: e.detail
    })
  },

  navToPlanPage() {
    wx.switchTab({
      url: "/pages/plan/plan"
    })
  },

  async play(e) {
    const _this = this;
    const openid = this.data.openid
    const id = e.currentTarget.dataset.id;
    const index = e.currentTarget.dataset.index;
    const date = _this.data.taskData.detail[index].act_date;
    const music = await Api.getMusic(openid, id, date);
    if (music.status == 0) {
      wx.showLoading({
        title: '加载中...',
      })
      player.title = date;
      const src = Config.baseUrl + music.data.url;
      player.src = src;
      player.play()
      player.seek(0)
      // player.seek(179)
      wx.hideTabBar()
      _this.setData({
        taskDataDetailIndex: index,
        onMusicEnd: false
      })
    } else {
      wx.showToast({
        title: music.msg,
        icon: 'none'
      })
    }

  },

  pause() {
    player.pause();
    this.setData({
      onMusicPlaying: false
    })
    wx.showTabBar()
  },
  kuaijin() {
    var music_length = this.data.taskData.music_length != 0 ? this.data.taskData.music_length : 3
    console.log(music_length);

    player.seek(music_length * 60 - 5)
  },
  handleShareClick(e) {
    if (e.currentTarget.dataset.type == "friend") {

    } else {
      this.setData({
        sharePicShow: true
      })
    }
  },
  closeSharePic() {

    this.setData({
      sharePicShow: false
    })
  },

  savePic() {
    let that = this
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
          })
        } else if (res.authSetting['scope.writePhotosAlbum'] === false) {
          wx.showModal({
            content: '检测到您未授予小程序 “保存图片到系统相册” 的权限，是否去设置打开？',
            success(res) {
              if (res.confirm) {
                wx.openSetting()
              }
            }
          })
        } else {
          that.loadImg()
        }
      }
    })
  },

  loadImg() {
    wx.saveImageToPhotosAlbum({
      filePath: "/assets/images/share-pic.png",
      success() {
        wx.showToast({
          title: '图片已保存到手机，请到朋友圈分享',
          icon:"none",
          duration: 1500
        })
      },
      fail() {
        wx.hideLoading()
      }
    })
  }
})

function setPlayer() {
  // player.autoplay = true
  player.onPlay(function () {
    if (!this.data.inMePage) return
    let data = this.data.taskData
    var music_length = data.music_length != 0 ? data.music_length : 3
    let duration = formatTime(music_length * 60);
    wx.hideLoading();

    this.setData({
      onMusicPlaying: true,
      ["timers[" + this.data.taskDataDetailIndex + "]"]: '0:00/' + duration
    })
  }.bind(this))


  // player.onPause(function () {
  //   this.setData({
  //     onMusicPlaying: false,
  //   })
  // }.bind(this))
  // player.onStop(function () {
  //   this.setData({
  //     onMusicPlaying: false,
  //   })
  // }.bind(this))

  player.onTimeUpdate(function () {
    if (!this.data.inMePage) return
    let data = this.data.taskData
    var music_length = data.music_length != 0 ? data.music_length : 3
    let duration = formatTime(music_length * 60);
    const currentTime = formatTime(player.currentTime);
    this.setData({
      progress: (player.currentTime / music_length / 60) * 100 + "%",
      ["timers[" + this.data.taskDataDetailIndex + "]"]: currentTime + '/' + duration,
    })
    if (player.currentTime >= music_length * 60) {
      musicComplete.call(this)
    }
  }.bind(this))

  async function musicComplete() {
    player.stop();
    var openid = this.data.openid;
    var id = this.data.taskData.id
    var detail = this.data.taskData.detail[this.data.taskDataDetailIndex]
    if (detail.complete == 0) {
      var res = await Api.settingcomplete(openid, id, detail.act_date)
      if (res.status == "0") {
        this.setData({
          onMusicEnd: true
        })
        this.getTaskList()
      } else {
        wx.showToast({
          title: '数据请求失败',
          icon: 'none'
        })
      }
    } else {
      this.setData({
        onMusicEnd: true
      })
    }

    var day = this.data.taskData.detail.filter(each => {
      if (each.complete == 1) {
        return each
      }
    }).length, tip;
    switch (day) {
      // case 1: tip = this.data.tips[0]; break;
      case 7: tip = this.data.tips[3]; break;
      case 14: tip = this.data.tips[4]; break;
      case 21: tip = this.data.tips[5]; break;
      default: tip = this.data.tips[Math.floor(Math.random() * 3)]; break;
    }
    this.setData({
      tip
    })
  }
}

function formatTime(s) {
  let h;
  h = Math.floor(s / 60);
  s = Math.floor(s) % 60;
  h += '';
  s += '';
  // h = (h.length == 1) ? '0' + h : h;
  s = (s.length == 1) ? '0' + s : s;
  return h + ':' + s;
}